<!--sellAllow  -->
<template>
  <div class="sellAllow content_box">
    <div class="header_row flex align-center flex-wrap" v-if="hasBtn('sellAllow:query')">
      <div class="flex align-center m-r-2">
        <span>方案名称：</span>
        <el-input v-model="searchObj.Name" clearable placeholder="搜索方案名称"></el-input>
      </div>

      <div class="flex align-center m-r-2">
        <span>时间：</span>
        <el-date-picker v-model="searchObj.timeValue" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" clearable>
        </el-date-picker>
      </div>
      <!-- 新增的下拉框 -->
      <div class="flex align-center m-r-2">
        <span>方案类型：</span>
        <el-select v-model="value" placeholder="所有方案">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>

      <el-button type="primary" @click="(searchObj.currentPage = 1), getListFun()">查询</el-button>
    </div>

    <div class="m-b-1 neck_box flex align-center space-between">
      <div>
        <el-button type="success" @click="showDialog('add')" v-if="hasBtn('sellAllow:add')">新增方案</el-button>
        <!-- <el-button type="danger">批量删除</el-button> -->
        <el-button type="warning" disabled v-if="hasBtn('sellAllow:export')">导出列表</el-button>
      </div>
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="searchObj.currentPage" :max-height="tableHeight" :page-size="searchObj.pageSize" :page-sizes="[10, 20, 50, 100, 200]" layout="total,sizes, prev, pager, next, jumper" :total="pageTotal">
      </el-pagination>
    </div>
    <el-table :data="tableData" border style="width: 100%" @sort-change="sortChange" sortable="custom" v-loading="tableLoading" stripe row-key="Id" @expand-change="expand">
      <el-table-column fixed type="expand">
        <template slot-scope="{ row }">

          <div class="table-expand">
            <div class="table-expand-boxs" :class=" idx%2 == 0 ? '' : 'box-bg' " v-for="(cell, idx) of row.Settings" :key="idx">
              <div class="table-expand-box">{{ cell.Sname }}</div>
              <div class="flex-table-expand">
                <div class="table-expand-box">{{ '达标金额: ' + cell.Target + '个' }}</div>
                <div class="table-expand-box">{{ '奖励金额: ' + cell.Award + '元' }}</div>
              </div>
            </div>
          </div>

          <!-- <div
            v-if="row.Settings"
            class="flex m-t-1 align-center space-between ladder_item"
          >
            <div class="flex-1">
              <div
                class="flex align-center space-between ladder_cell"
                v-for="(cell, idx) of row.Settings"
                :key="idx"
              >
                <div class="flex align-center m-r-1">
                  <span class="tit_span nowarp">{{ cell.Sname }}</span>
                </div>
                <div class="info_group">
                  <div class="flex align-center">
                    <span class="tit_span nowarp">激活目标：</span>
                    <span class="nowarp">{{ cell.Target }}个</span>
                  </div>
                  <div class="flex align-center">
                    <span class="tit_span nowarp">奖励金额：</span>
                    <span class="nowarp">{{ cell.Award }}元</span>
                  </div>

                  --------旧代码注释部分---
                  <div class="flex align-center">
                    <span class="tit_span nowarp">开始时间：</span>
                    <span class="nowarp">{{ cell.StartTime }}</span>
                  </div>
                  <div class="flex align-center">
                    <span class="tit_span nowarp">结束时间：</span>
                    <span class="nowarp">{{ cell.EndTime }}</span>
                  </div>
                  ---------------

                </div>
              </div>
            </div>
          </div>
          <span v-else>暂无阶梯方案</span> -->
        </template>
      </el-table-column>
      <el-table-column fixed prop="index" label="序号" width="80" align="center">
      </el-table-column>
      <el-table-column prop="Sname" label="方案名称" align="center" sortable>
      </el-table-column>
      <!-- <el-table-column prop="Target" label="销售目标：" align="center" sortable>
      </el-table-column>
      <el-table-column prop="Award" label="奖励金额" align="center" sortable>
      </el-table-column> -->

      <el-table-column prop="IsSystem" label="方案类型" align="center" sortable>
        <template slot-scope="scope">
          <div>
            {{
              scope.row.IsSystem == 1
                ? "系统方案"
                : scope.row.IsSystem == 2
                ? "身份方案"
                : scope.row.IsSystem == 3
                ? "公司方案"
                : "机构团队方案"
            }}
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="UserName" label="方案所属" align="center">
      </el-table-column> -->
      <el-table-column prop="Remark" label="备注" align="center" sortable>
      </el-table-column>
      <el-table-column prop="CreateBy" label="创建人员" align="center" sortable>
      </el-table-column>
      <el-table-column prop="CreateDate" label="创建时间" align="center" width="180" sortable>
      </el-table-column>
      <el-table-column prop="UpdateBy" label="修改人员" align="center" sortable>
      </el-table-column>
      <el-table-column prop="UpdateDate" label="修改时间" align="center" sortable width="180">
      </el-table-column>
      <el-table-column label="是否有效" align="center" sortable>
        <template slot-scope="scope">
          <!-- :disabled="!hasBtn('sellAllow:active') ? true : !(scope.row.IsSystem == 1)" switch除系统身份不能编辑 -->
          <el-switch v-model="scope.row.IsActive" :disabled="!hasBtn('sellAllow:active')" @change="switchChange(scope.row.Id, scope.row.IsActive)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150" align="center" v-if="hasBtn('sellAllow:edit') || hasBtn('sellAllow:delete')">
        <template slot-scope="scope">
          <!-- :disabled="!(scope.row.IsSystem == 1)" 编辑button除系统身份不能编辑 -->
          <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)" v-if="hasBtn('sellAllow:edit')">编辑</el-button>
          <el-button @click="handleDelete(scope.$index, scope.row)" v-if="hasBtn('sellAllow:delete')" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="dialogTitle" class="dialog" :visible.sync="dialogVisible" width="800px">
      <el-form ref="dataForm" :rules="rules" :model="addObj" label-position="right" label-width="140px">
        <el-form-item label="方案名称：" prop="SName">
          <el-input class="flex-1" v-model="addObj.SName"></el-input>
        </el-form-item>
        <!-- <el-form-item label="销售目标：" prop="Target">
          <el-input
            class="flex-1"
            v-model="addObj.Target"
            placeholder="请输入内容"
            type="number"
            ><template slot="append">元</template></el-input
          >
        </el-form-item>
        <el-form-item label="奖励金额：" prop="Award">
          <el-input
            class="flex-1"
            v-model="addObj.Award"
            placeholder="请输入内容"
            type="number"
            ><template slot="append">元</template></el-input
          >
        </el-form-item> -->

        <el-form-item label="备注：" prop="Remark">
          <el-input type="textarea" class="flex-1" v-model="addObj.Remark" placeholder="请输入内容" maxlength="30" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div class="m-t-1 m-b-1 float_none">
        <el-button class="float_right" @click="addladderArray">新增档次</el-button>
      </div>
      <div class="auto-scroll">
        <div class="flex m-t-1 align-center space-between ladder_item">
          <div class="flex-1">
            <div class="flex align-center space-between ladder_cell" v-for="(cell, idx) of addObj.Settings" :key="idx">
              <i class="el-icon-circle-close m-r-1" @click="deleteladderArray(idx)"></i>
              <div class="m-r-2">
                <div class="flex align-center">
                  <el-input class="ladder_SName" v-model="cell.Sname" placeholder="档次名"></el-input>
                </div>

                <!-- <el-date-picker
                  class="flex-1"
                  v-model="cell.timeValue"
                  value-format="yyyy-MM-dd hh:mm:ss"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                >
                </el-date-picker> -->
              </div>
              <div class="info_group">
                <div class="flex align-center">
                  <span class="tit_span nowarp">激活目标：</span>
                  <el-input type="number" v-model="cell.Target" min="0" @keyup.native="proving2($event)" class="flex-1">
                    <template slot="append">个</template>
                  </el-input>
                </div>
                <div class="flex align-center">
                  <span class="tit_span nowarp">奖励金额：</span>
                  <el-input type="number" v-model="cell.Award" min="0" @keyup.native="proving2($event)" class="flex-1">
                    <template slot="append">元</template>
                  </el-input>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button @click="saveData">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { getList, save, deleteApi, valid, getExpandDetail } from '@/api/EquityManage/sellAllow'

  export default {
    //import引入的组件需要注入到对象中才能使用
    name: 'sellAllow',
    components: {},
    data() {
      //这里存放数据
      return {
        options: [ //下拉框值
          {
            value: 0,
            label: '所有方案'
          },
          {
            value: 2,
            label: '身份方案'
          },
          {
            value: 1,
            label: '系统方案'
          },
          // {
          //   value: 3,
          //   label: '公司方案'
          // },
          {
            value: 4,
            label: '团队方案'
          }
        ],
        value: 0, //下拉框显示的值
        tableLoading: false,
        dialogVisible: false,
        dialogType: "add",
        searchObj: {
          Name: "",
          timeValue: "",
          currentPage: 1,
          pageSize: 10,
        },
        pageTotal: 0,
        tableHeight: 0,
        tableData: [],
        rules: {
          SName: [
            { required: true, message: '必填', trigger: 'blur' },
          ],
          // Target: [
          //   { required: true, message: '必填', trigger: 'blur' },
          // ],
          // Award: [
          //   { required: true, message: '必填', trigger: 'blur' },
          // ],
        },
        addObj: {},
        objTmp: {
          "Id": "00000000-0000-0000-0000-000000000000",
          "SName": "", //方案名称
          'IsSystem': 1,
          "Remark": "",
          "Settings": [
            {
              "Id": "00000000-0000-0000-0000-000000000000", //新增：00000000-0000-0000-0000-000000000000，则为修改
              "Sname": "", //方案名称
              "Target": 0, //达标金额
              "Award": 0, //奖励金额
              "SerialNum": 1,
            }
          ]
        }
      };
    },
    //监听属性 类似于data概念
    computed: {
      dialogTitle() {
        return this.dialogType == 'add' ? '新增方案' : '编辑方案'
      },
    },
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
      expand(row, expand) {
        console.log(row)
        if (!row.OpenExpand) {
          row.OpenExpand = true
          this.getDetail(row)
        }
      },
      async getDetail(row) {
        const { data } = await getExpandDetail({
          Id: row.Id
        })
        // row.Mains = data.Mains
        this.$set(row, 'Settings', data.Settings)
      },
      switchChange(id, IsActive) {
        valid({ Id: id }).then(_ => {
          this.$notify({
            title: '切换成功',
            message: 'success',
            type: 'success',
            duration: 2000
          })
          this.getListFun()
        })
      },
      showDialog(type) {
        if (type == 'add') {
          this.addObj = this.objTmp
        }
        this.dialogType = type
        this.dialogVisible = true

      },
      saveData() {
        console.log(this.addObj)
        for (let item in this.addObj) {
          if (['Remark'].includes(item)) continue
          if (!this.addObj[item] && this.addObj[item] !== 'Number') {
            this.$notify({
              title: '提示',
              message: '请填写完整信息',
              type: 'warning',
              duration: 2000
            })
            return
          }
        }
        let addObj = this.$deepClone(this.addObj)
        // for (let item of addObj.Settings) {
        //   if (!item.timeValue) {
        //     this.$notify({
        //       title: '提示',
        //       message: '阶段请填写时间',
        //       type: 'warning',
        //       duration: 2000
        //     })
        //     return
        //   }
        //   item.StartTime = item.timeValue[0]
        //   item.EndTime = item.timeValue[1]
        //   delete item.timeValue
        // }

        save(addObj).then(res => {
          this.$notify({
            title: '保存成功',
            message: 'success',
            type: 'success',
            duration: 2000
          })
          this.dialogVisible = false
          this.getListFun()
        }).catch(err => {

        })
      },
      handleSizeChange(val) {
        this.searchObj.pageSize = val
        this.getListFun()
      },
      handleCurrentChange(val) {
        this.searchObj.currentPage = val
        this.getListFun()
      },
      async handleEdit(index, row) {
        let { Data } = await getExpandDetail({
          Id: row.Id
        })
        this.addObj = {
          "Id": Data.Id,
          "SName": Data.Sname, //方案名称
          'IsSystem': Data.IsSystem,
          "Remark": Data.Remark,
          "Settings": Data.Settings
        }
        // for (let item of this.addObj.Settings) {
        //   item.timeValue = []
        //   item.timeValue[0] = item.StartTime
        //   item.timeValue[1] = item.EndTime
        // }
        // this.$forceUpdate()
        this.showDialog('edit')
      },
      handleDelete(index, row) {
        this.$confirm('确认删除此条数据吗？').then(_ => {
          let obj = {
            Id: row.Id
          }
          deleteApi(obj).then(res => {

            this.$notify({
              title: '删除成功',
              message: 'success',
              type: 'success',
              duration: 2000
            })
            this.tableData.splice(index, 1)
            this.pageTotal -= 1
          })
        })


      },
      sortChange(e) {
        let SortType = false
        if (e.order == "ascending") {
          SortType = true
        }
        this.getListFun(e.prop, SortType)
      },
      getListFun(SortName = 'CreateDate', SortType = true) {
        let currentPage = this.searchObj.currentPage
        this.tableLoading = true
        let searchObj = this.$deepClone(this.searchObj)
        let value = this.value
        let obj = {
          "Name": searchObj.Name, //	模块：指定整体管理模块设定
          "IsPaging": true, //是否分页
          "SortName": SortName, //排序栏位
          "SortType": SortType,//排序类型｛True：正序；Flase：反序｝
          'PageIndex': currentPage,
          "PageSize": this.searchObj.pageSize,
          'IsSystem': value
        }
        searchObj.timeValue && (obj['StartTime'] = searchObj.timeValue[0])//开始时间
        searchObj.timeValue && (obj['EndTime'] = searchObj.timeValue[1])//结束时间
        delete searchObj.timeValue
        getList(obj).then(res => {
          this.tableData = res.Data.map((item, index) => {
            for (let cell in item) {
              if (!item[cell] && this.$getType(item[cell]) !== 'Number') {
                item[cell] = '-'
              }
            }
            return { ...item, index: (index + 1) + ((currentPage - 1) * 10) }
          })
          this.pageTotal = res.Total
          this.tableLoading = false
        }).catch(_ => {
          this.tableLoading = false
          this.tableData = []
          this.pageTotal = 0
        })
      },
      addladderArray() {
        let num = this.addObj.Settings.length
        this.addObj.Settings.push({
          "Id": "00000000-0000-0000-0000-000000000000", //新增：00000000-0000-0000-0000-000000000000，则为修改
          "Sname": "", //方案名称
          "Target": 0, //达标金额
          "Award": 0, //奖励金额
          "SerialNum": num + 1,
          // 'timeValue': ''
          // "StartTime": "", //开始时间
          // "EndTime": "" //结束时间
        })
      },
      deleteladderArray(index) {
        this.addObj.Settings.splice(index, 1)
      }
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
      this.getListFun()
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {

    },
    beforeCreate() { }, //生命周期 - 创建之前
    beforeMount() { }, //生命周期 - 挂载之前
    beforeUpdate() { }, //生命周期 - 更新之前
    updated() { }, //生命周期 - 更新之后
    beforeDestroy() { }, //生命周期 - 销毁之前
    destroyed() { }, //生命周期 - 销毁完成
    activated() { }, //如果页面有keep-alive缓存功能，这个函数会触发
  }
</script>
//@import url(); 引入公共css类
<style  scoped>
  .info_group {
    width: 65%;
  }
  /* .promoteB >>> .el-dialog {
      min-width: 560px;
    } */

  .ladder_item {
    width: 95%;
    border-bottom: 1px solid #cecece;
    padding: 5px 0;
  }
  .ladder_cell + .ladder_cell {
    border-top: 2px dashed #f6bcbc;
  }
  .ladder_cell {
    padding: 5px 0;
  }
  .ladder_name {
    /* width: 100px !important; */
    margin-right: 3%;
  }

  .el-icon-circle-close {
    font-size: 18px;
    transition: color 0.25s linear;
  }
  .el-icon-circle-close:hover {
    color: #cecece;
    cursor: pointer;
  }
  .table_ladname {
    width: 30%;
    font-size: 16px;
  }
  .table-expand-box {
    width: 30%;
  }
  .flex-table-expand {
    display: flex;
    width: 70%;
  }
  .flex-table-expand .table-expand-box {
    width: 50%;
  }
</style>